import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:fluwx/fluwx.dart';
import 'package:get/get.dart';
import '../../config/config.dart';
import '../../model/recharge_model.dart';
import '../../model/user_data.dart';
import '../../model/wx_pay_model.dart';
import '../../request/api.dart';
import '../../request/requestManager.dart';
import '../../utils/log_utils.dart';
import '../../utils/sp_utils.dart';

class RechargeController extends GetxController {
  UserData? userData;
  int coin = 0;
  int incomeCoin = 0;
  List<RechargeModel> channels = [];
  int channelIndex = 0;
  int channelItemIndex = 0;
  late Function(WeChatResponse) responseListener;
  Fluwx fluwx = Fluwx();
  @override
  void onInit() {
    super.onInit();
    getUserData();
    getGoodsList();
    // Fluwx().addSubscriber((response) {
    //   debugPrint('Flutter微信支付坚挺11 ${response}');
    // });
    // responseListener = ((response) {
    //   debugPrint('Flutter微信支付坚挺 ${response.isSuccessful}');
    //   if (response is WeChatPaymentResponse) {
    //     debugPrint('oninit responseListener ${response.isSuccessful}');
    //     if (response.isSuccessful) {
    //       print('支付成功');
    //     } else {
    //       print('支付失败:${response.errStr ?? response.toString()}');
    //     }
    //   } else {
    //     print('支付失败2:${response.errStr ?? response.toString()}');
    //   }
    // });
  }

  void getUserData() async {
    var result = await RequestManager().post(API.myInfo);
    if (result != null && result['code'] == 0) {
      UserData user = UserData.fromJson(result['data']);
      SpUtil.saveUserData(user);
      userData = user;
      update();
    }
  }

  void getGoodsList() async {
    var result =
        await RequestManager().post(API.getWallInfo, params: {'type': 0});

    if (result != null && result['code'] == 0) {
      Map data = result['data'];
      coin = data['coin'];
      incomeCoin = data['income_coin'];
      List channelsData = data['channels'];
      for (var element in channelsData) {
        RechargeModel m = RechargeModel.fromJson(element);
        channels.add(m);
      }

      // channelsData.forEach((element) {
      //   RechargeModel m = RechargeModel.fromJson(element);
      //   channels.add(m);
      // });
      update();
    }
  }

  List<GoodsItem> getSelectGoodsList() {
    if (channels.isEmpty) return [];
    return channels[channelIndex].goodsList ?? [];
  }

  // 选择充值选项
  void selectItem(int index) {
    channelItemIndex = index;
    update();
  }

  // 选择支付方式
  void selectPayMentType(int index) {
    channelItemIndex = 0;
    channelIndex = index;
    update();
  }

  // 充值
  void rechargeClick() {
    // TODO: - 充值
    // print('channel:${channels[channelIndex].channelName}');
    // print('goods_id:${channels[channelIndex].goodsList?[channelItemIndex].id}');
    if (channelIndex == 1) {
      // 微信支付
      // payForWx(channels[channelIndex].goodsList?[channelItemIndex].id ?? 0);
    }
  }

  void payForWx(int goodId) async {
    if (goodId == 0) return;
    bool isInstalled = await fluwx.isWeChatInstalled;
    if (!isInstalled) {
      EasyLoading.showToast('请先安装微信');
      return;
    }

    // 微信支付参数
    Map params = {'channel': 1, 'goods_id': goodId};
    var result =
        await RequestManager().post(API.walletRecharge, params: params);
    WJLogUtils.wjLog(result);
    if (result != null && result['code'] == 0) {
      WxPayModel wxPayModel = WxPayModel.fromJson(result['data']);
      // print('打开微信支付appid:${wxPayModel.wechatpayinfo!.appid!}');
      Wechatpayinfo? info = wxPayModel.wechatpayinfo;
      if (info == null) return;
      fluwx.registerApi(
          appId: 'wx6aad49519ad6ac7d', universalLink: AppConfig.universalLink);
      fluwx
          .pay(
              which: Payment(
                  appId: info.appid ?? '',
                  partnerId: info.partnerid ?? '',
                  prepayId: info.prepayid ?? '',
                  packageValue: info.package ?? '',
                  nonceStr: info.noncestr ?? '',
                  timestamp: info.timestamp ?? 0,
                  sign: info.sign ?? ''))
          .then((value) {
        debugPrint('Flutter微信支付监听 ${value.toString()}');
      }).catchError((e) {
        debugPrint('Flutter微信支付异常 ${e.toString()}');
      });
    }
  }
}
